import { busEnum } from './enum'

// 事件总线
type Fn = (...args: any[]) => void

export class EventEmitter {
  private _events: {
    [key: string]: Fn[]
  } = {}

  on(event: busEnum, fn: (data: any) => void) {
    if (!this._events[event]) {
      this._events[event] = []
    }
    this._events[event].push(fn)
  }

  emit(event: busEnum, ...args: any[]) {
    if (!this._events[event]) {
      return
    }
    this._events[event].forEach((fn) => {
      fn(...args)
    })
  }

  off(event: busEnum, fn: (data: any) => void) {
    if (!this._events[event]) {
      return
    }
    this._events[event] = this._events[event].filter((f) => f !== fn)
  }
}

export default new EventEmitter()
